from django.shortcuts import render, HttpResponse
from app01 import models


# Create your views here.
def reg(request):
    user, user_error = '', ''
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        # 对数据做校验
        if len(user) <= 6:
            user_error = '用户名太短了'

        # 校验不成功 返回填写的数据 错误的提示

        # 校验成功 保存数据库
    return render(request, 'reg.html', {'user': user, 'user_error': user_error})


from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, RegexValidator


def check_user(value):
    if 'alex' in value:
        raise ValidationError('alex 不配！！ ')


class RegForm(forms.Form):
    user = forms.CharField(label='用户名', initial='张三',disabled=True, validators=[check_user, ])
    pwd = forms.CharField(
        label='密码',
        widget=forms.PasswordInput,
        # required=False,
        min_length=6,
        max_length=10,
        error_messages={
            'required': '该字段是必填的~',
            'min_length': '至少是6位。'
        }

    )
    re_pwd = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput,
        # required=False,
        min_length=6,
        max_length=10,
        error_messages={
            'required': '该字段是必填的~',
            'min_length': '至少是6位。'
        }

    )

    gender = forms.ChoiceField(
        choices=((1, '男'), (2, '女'), (3, 'alex')),
        widget=forms.RadioSelect
    )
    phone = forms.CharField(validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式不正确')])
    # hobby = forms.MultipleChoiceField(
    #     initial=[1,2],
    #     # choices=((1, "篮球"), (2, "足球"), (3, "双色球"),),
    #     choices=models.Hobby.objects.values_list('id','name'),
    #     widget=forms.CheckboxSelectMultiple
    # )

    hobby = forms.ModelMultipleChoiceField(
        initial=[1, 2],
        queryset=models.Hobby.objects.all(),
        widget=forms.CheckboxSelectMultiple
    )
    birth = forms.DateTimeField()

    def clean_gender(self):
        v = self.cleaned_data.get('gender')
        # 局部钩子
        # 不通过校验 抛出异常
        # 通过校验   必须返回当前字段的值
        return v

    def clean(self):
        # 全局钩子
        # 不通过校验 抛出异常
        # 通过校验   必须返回所有字段的值 self.cleaned_data
        pwd = self.cleaned_data.get('pwd')
        re_pwd = self.cleaned_data.get('re_pwd')
        if pwd != re_pwd:
            self.add_error('re_pwd','两次密码不一致!')
            raise ValidationError('两次密码不一致')
        return self.cleaned_data


def reg2(request):
    form_obj = RegForm()

    if request.method == 'POST':
        form_obj = RegForm(data=request.POST)
        if form_obj.is_valid():  # 做校验
            # 插入数据库
            return HttpResponse('ok')

    return render(request, 'reg2.html', {'form_obj': form_obj})
